<template>
  <div class="flex flex-col">
    <div class="font-[600] text-lg text-black">{{ pieTitle }}</div>
    <div class="flex-1 w-full" ref="pieRef"></div>
  </div>
</template>
<script setup>
import { ref, onBeforeUnmount } from 'vue'

import echarts from '@/utils/echarts'

const pieRef = ref(null)
const pieCharts = ref(null)
const pieTitle = ref('')
const getPieOption = (titleText, seriesData) => {
  return {
    title: {
      show: false,
      text: titleText,
      left: 'left',
      textStyle: {
        color: '#000',
        fontSize: 18,
        fontWeight: '600',
      },
    },
    tooltip: {
      trigger: 'item',
    },

    legend: {
      bottom: '1%',
      left: 'center',
    },
    color: ['#5a89e7', '#78b9c3', '#67a361'],
    series: [
      {
        type: 'pie',
        radius: '60%',
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 4,
          borderWidth: 2,
        },
        label: {
          show: false,
        },
        labelLine: {
          show: false,
        },
        data: seriesData,
      },
    ],
  }
}
const initData = (title, data) => {
  pieCharts.value = null
  pieTitle.value = title
  const pie = echarts.init(pieRef.value)
  pie.setOption(getPieOption(title, data))
  pieCharts.value = pie
  window.addEventListener('resize', handleResize)
}

const handleResize = () => {
  pieCharts.value.resize()
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  pieCharts.value.dispose()
})

defineExpose({
  initData,
})
</script>
<style lang="scss" scoped></style>
